package com.gxa.ehome.controller;

import com.gxa.ehome.util.MapUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

@Controller
@ResponseBody
public class UploadController {
    //@RequestMapping(value = "/upload",method = RequestMethod.POST)

    //通过MultipartFile对象接收前端传递的图像数据,基于layui会只能
    //用file获取目标参数名(默认,不能修改)
    //HttpServletRequest为了获取Context,从而获取"/"真实路径
    @PostMapping(value = "/upload")
    public Map<String,Object> upload(@RequestParam("file")MultipartFile multipartFile, HttpServletRequest request) throws IOException {

        String filename = multipartFile.getOriginalFilename();
        System.out.println(filename);
        //从原始文件名中获取后缀,作为新添加的文件的文件名后缀
        String subfix=filename.substring(filename.indexOf(".")+1);
        System.out.println(subfix);
        String targetFile= UUID.randomUUID().toString()+"."+subfix;
        System.out.println(targetFile);

        //通过request获取当前程序的根路径"/"
        String path=request.getServletContext().getRealPath("/");
        String fileName=path+"static/uploadImg/"+targetFile;
        System.out.println(fileName);
        //构建文件对象
        File uploadFile=new File(fileName);

        //核心操作
        try {
            multipartFile.transferTo(uploadFile);
        } catch (IOException e) {
        //e.printStackTrace();
            throw e;
        }
        MapUtil mapUtil = new MapUtil();
        //返回状态:0表示上传成功
        mapUtil.setCode("0");
        //返回服务器保存后的文件名
        mapUtil.put("fileName",targetFile);
        return mapUtil.getValues();
    }
}
